package com.ruoyi.job.service;

import cn.hutool.core.bean.BeanUtil;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.approval.v4.model.GetInstanceReq;
import com.lark.oapi.service.approval.v4.model.GetInstanceResp;
import com.lark.oapi.service.contact.v3.model.FindByDepartmentUserReq;
import com.lark.oapi.service.contact.v3.model.FindByDepartmentUserResp;
import com.lark.oapi.service.contact.v3.model.User;
import com.ruoyi.GetToken;
import com.ruoyi.baseMain.domain.bo.BaseAccountBo;
import com.ruoyi.baseMain.domain.bo.BaseCustomBo;
import com.ruoyi.baseMain.domain.bo.BasePolicyBo;
import com.ruoyi.baseMain.domain.bo.BasePolicyHisBo;
import com.ruoyi.baseMain.domain.vo.BaseAccountVo;
import com.ruoyi.baseMain.domain.vo.BasePolicyHisVo;
import com.ruoyi.baseMain.domain.vo.BasePolicyVo;
import com.ruoyi.baseMain.service.IBaseCustomService;
import com.ruoyi.baseMain.service.IBasePolicyHisService;
import com.ruoyi.baseMain.service.IBasePolicyService;
import com.ruoyi.baseMain.service.impl.BaseAccountServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * XxlJob开发示例（Bean模式）
 * <p>
 * 开发步骤：
 * 1、任务开发：在Spring Bean实例中，开发Job方法；
 * 2、注解配置：为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobHelper.log" 打印执行日志；
 * 4、任务结果：默认任务结果为 "成功" 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果；
 *
 * @author xuxueli 2019-12-11 21:52:51
 */
@Slf4j
@Service
public class FeishuJobService {
    private final IBasePolicyService iBasePolicyService;
    private final IBasePolicyHisService iBasePolicyHisService;
    private final IBaseCustomService iBaseCustomService;
    private final ISysUserService iSysUserService;
    private ISysDeptService iSysDeptService;
    private BaseAccountServiceImpl baseAccountServiceImpl;

    public FeishuJobService(BaseAccountServiceImpl baseAccountServiceImpl,ISysDeptService iSysDeptService,IBasePolicyService iBasePolicyService, IBasePolicyHisService iBasePolicyHisService, IBaseCustomService iBaseCustomService, ISysUserService iSysUserService) {
        this.iBasePolicyService = iBasePolicyService;
        this.iBasePolicyHisService = iBasePolicyHisService;
        this.iBaseCustomService = iBaseCustomService;
        this.iSysUserService = iSysUserService;
        this.iSysDeptService = iSysDeptService;
        this.baseAccountServiceImpl = baseAccountServiceImpl;
    }

    @XxlJob("UpdatePolicyToAccount")
    public void UpdatePolicyToAccount() throws Exception {
        //每日更新审批好的客户政策到开户表中   List<BasePolicyVo> queryList(BasePolicyBo bo);
        BasePolicyBo basePolicyBo = new BasePolicyBo();
        basePolicyBo.setStatus("1");
        List<BasePolicyVo> list = iBasePolicyService.queryList(basePolicyBo);
        for (BasePolicyVo basePolicyVo : list) {
            BaseAccountBo bo = new BaseAccountBo();
            //现在是查询客户一样合作媒体一样政策一样的开户信息
            bo.setCustomName(basePolicyVo.getNickName());
            bo.setSignatory(basePolicyVo.getSignatory());
            bo.setBidding(basePolicyVo.getPolicyType());
            List<BaseAccountVo> baseAccountVos = baseAccountServiceImpl.queryList(bo);
            List<BaseAccountBo> baseAccountBos = BeanUtil.copyToList(baseAccountVos, BaseAccountBo.class);
            for (BaseAccountBo baseAccountBo : baseAccountBos) {
                baseAccountBo.setPoint(basePolicyBo.getTotalPoint());
                baseAccountBo.setSaleUserName(basePolicyBo.getOperateUserName());
                baseAccountServiceImpl.updateByBo(baseAccountBo);
            }
        }
    }

    @XxlJob("UpdateCusTaskStatus")
    public void UpdateCusTaskStatus() throws Exception {
        GetToken getToken = new GetToken();
        Client client = Client.newBuilder(getToken.appId, getToken.appSecret).build();
        List<BaseCustomBo> list = iBaseCustomService.queryListInstanceIdIsNotNull();
        for (BaseCustomBo baseCustomBo : list) {
            GetInstanceReq req = GetInstanceReq.newBuilder()
                .instanceId(baseCustomBo.getInstanceCode())
//            .locale("zh-CN")
//            .userId("f7cb567e")
//            .userIdType("user_id")
                .build(); GetInstanceResp resp = client.approval().v4().instance().get(req);
            if(baseCustomBo.getStatus().equals("1")&&!Objects.isNull(baseCustomBo.getSigns()) && baseCustomBo.getSigns().equals("审核中")){
                if (resp.getData().getStatus().equals("APPROVED")) {
                    //通过
                    baseCustomBo.setSigns("已签署");

                }else if(resp.getData().getStatus().equals("REJECTED")){
                    //拒绝
                    baseCustomBo.setSigns("未签署");
                }
            }else{
                if (resp.getData().getStatus().equals("APPROVED")) {
                    //通过
                    baseCustomBo.setStatus("1");
                }else if(resp.getData().getStatus().equals("REJECTED")){
                    //拒绝
                    baseCustomBo.setStatus("0");
                }


            }

            iBaseCustomService.updateByBo(baseCustomBo);
        }
    }
    @XxlJob("UpdateTaskStatus")
    public void UpdateTaskStatus() throws Exception {
        GetToken getToken = new GetToken();
        Client client = Client.newBuilder(getToken.appId, getToken.appSecret).build();

        List<BasePolicyBo> list = iBasePolicyService.queryListInstanceIdIsNotNull();
        for (BasePolicyBo basePolicyBo : list) {
            // 创建请求对象
            GetInstanceReq req = GetInstanceReq.newBuilder()
                .instanceId(basePolicyBo.getInstanceCode())
//            .locale("zh-CN")
//            .userId("f7cb567e")
//            .userIdType("user_id")
                .build();

            // 发起请求
            GetInstanceResp resp = client.approval().v4().instance().get(req);
            if (resp.getData().getStatus().equals("APPROVED")) {
                // 审批通过
                BasePolicyHisBo basePolicyHisBo = new BasePolicyHisBo();
                basePolicyHisBo.setInstanceCode(resp.getData().getInstanceCode());

                List<BasePolicyHisVo> basePolicyHisVos = iBasePolicyHisService.queryList(basePolicyHisBo);
                if (basePolicyHisVos.size() == 1) {
                    if (basePolicyHisVos.get(0).getStatus().equals("2") || basePolicyHisVos.get(0).getStatus().equals("4")) {
                        //先判断是否到达生效日期
                        String status;
                        if (System.currentTimeMillis() < basePolicyBo.getTakeTime().getTime()) {
                            status = "4";
                        } else {
                            status = "1";
                            //需要反写 返点 和销售人员
//                            SysUser sysUser = iSysUserService.selectUserByRemark(resp.getData().getOpenId());
                            BaseAccountBo bo = new BaseAccountBo();
                            //现在是查询客户一样合作媒体一样政策一样的开户信息
                            bo.setCustomName(basePolicyBo.getNickName());
                            bo.setSignatory(basePolicyBo.getSignatory());
                            bo.setBidding(basePolicyBo.getPolicyType());
                            //政策标签（即开户标签
                            bo.setAccountTag(basePolicyBo.getPolicyTag());
                            List<BaseAccountVo> baseAccountVos = baseAccountServiceImpl.queryList(bo);
                            List<BaseAccountBo> baseAccountBos = BeanUtil.copyToList(baseAccountVos, BaseAccountBo.class);
                            for (BaseAccountBo baseAccountBo : baseAccountBos) {
                                baseAccountBo.setPoint(basePolicyBo.getTotalPoint());
                                baseAccountBo.setSaleUserName(basePolicyBo.getOperateUserName());
                                baseAccountServiceImpl.updateByBo(baseAccountBo);
                            }
                        }
                        BasePolicyBo basePBo = BeanUtil.toBean(basePolicyHisVos.get(0), BasePolicyBo.class);
                        BasePolicyHisBo hbo = BeanUtil.toBean(basePolicyHisVos.get(0), BasePolicyHisBo.class);
                        basePBo.setId(basePolicyHisVos.get(0).getPolicyId());
                        basePBo.setStatus(status);
                        iBasePolicyService.updateByBo(basePBo);
                        hbo.setStatus(status);
                        SysUser user = iSysUserService.selectUserByRemark(resp.getData().getOpenId());
                        String username = "";
                        String userId = "";
                        if (!Objects.isNull(user)) {
                            username = user.getNickName();
                            userId = user.getUserId().toString();
                        } else {
                            username = resp.getData().getOpenId();
                            userId = resp.getData().getOpenId();
                        }
                        hbo.setApproveUser(userId);
                        hbo.setApproveUserName(username);
                        iBasePolicyHisService.updateByBo(hbo);
                    }
                }
            } else if (resp.getData().getStatus().equals("REJECTED")) {
                // 审批拒绝
                BasePolicyHisBo basePolicyHisBo = new BasePolicyHisBo();
                basePolicyHisBo.setInstanceCode(resp.getData().getInstanceCode());


                List<BasePolicyHisVo> basePolicyHisVos = iBasePolicyHisService.queryList(basePolicyHisBo);
                if (list.size() == 1) {
                    if (list.get(0).getStatus().equals("2")) {
                        //更新数据
                        BasePolicyBo baseBo = BeanUtil.toBean(basePolicyHisVos.get(0), BasePolicyBo.class);
                        BasePolicyHisBo hbo = BeanUtil.toBean(basePolicyHisVos.get(0), BasePolicyHisBo.class);
                        baseBo.setId(basePolicyHisVos.get(0).getPolicyId());
                        baseBo.setStatus("3");
                        iBasePolicyService.updateByBo(baseBo);
                        hbo.setStatus("3");
                        SysUser user = iSysUserService.selectUserByRemark(resp.getData().getOpenId());
                        String username = "";
                        String userId = "";
                        if (!Objects.isNull(user)) {
                            username = user.getNickName();
                            userId = user.getUserId().toString();
                        } else {
                            username = resp.getData().getOpenId();
                            userId = resp.getData().getOpenId();
                        }
                        hbo.setApproveUser(userId);
                        hbo.setApproveUserName(username);
                        iBasePolicyHisService.updateByBo(hbo);
                    }
                }
            }
            // 业务数据处理  APPROVED  通过  PENDING  审批中  REJECTED 拒绝
            System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
        }
    }
    /**
     * 获取飞书流程状态
     */
    @XxlJob("FindByDepartment")
    public void FindByDepartment() throws Exception {
        // 构建client
        GetToken getToken = new GetToken();
        Client client = Client.newBuilder(getToken.appId, getToken.appSecret).build();
        List<SysDept> depts = iSysDeptService.findByDepartment();
        for (SysDept dept : depts) {
            if(dept.getDeptId()!=100L){
                // 创建请求对象
                FindByDepartmentUserReq req = FindByDepartmentUserReq.newBuilder()
                    .departmentId(dept.getDepartmentId())
                    .build();

                // 发起请求
                FindByDepartmentUserResp resp = client.contact().v3().user().findByDepartment(req);
                for (User item : resp.getData().getItems()) {
                    SysUser user = new SysUser();
                    user.setDeptId(dept.getDeptId());
                    user.setRemark(item.getOpenId());
                    user.setLeaderUserId(item.getLeaderUserId());
                    user.setNickName(item.getName());
                    user.setUserName(item.getMobile().replace("+86",""));
                    user.setUserType("sys_user");
                    SysUser temp = iSysUserService.selectUserByRemark(item.getOpenId());
                    if(Objects.isNull(temp)){
                        user.setPassword("$2a$10$L/MJa99w0byDT/b4mnv67uVURzYDSCmk54NkcZmUkmZU/idD8H9by");//123456
                        iSysUserService.insertUser(user);
                    }else{
                        iSysUserService.updateUserOnly(user);
                    }

                }

                // 处理服务端错误
                if (!resp.success()) {
                    System.out.println(String.format("code:%s,msg:%s,reqId:%s"
                        , resp.getCode(), resp.getMsg(), resp.getRequestId()));
                }
            }

        }

    }
    /**
     * 获取飞书流程状态
     */
    @XxlJob("GetTaskStatus")
    public void GetTaskStatus() throws Exception {
        GetToken getToken = new GetToken();
        Client client = Client.newBuilder(getToken.appId, getToken.appSecret).build();

        List<BasePolicyBo> list = iBasePolicyService.queryListInstanceIdIsNotNull();
        for (BasePolicyBo basePolicyBo : list) {
            // 创建请求对象
            GetInstanceReq req = GetInstanceReq.newBuilder()
                .instanceId(basePolicyBo.getInstanceCode())
//            .locale("zh-CN")
//            .userId("f7cb567e")
//            .userIdType("user_id")
                .build();

            // 发起请求
            GetInstanceResp resp = client.approval().v4().instance().get(req);
            if(resp.getData().getStatus().equals("APPROVED")){
                // 审批通过
                BasePolicyHisBo basePolicyHisBo = new BasePolicyHisBo();
                basePolicyHisBo.setInstanceCode(resp.getData().getInstanceCode());

                List<BasePolicyHisVo> basePolicyHisVos = iBasePolicyHisService.queryList(basePolicyHisBo);
                if(basePolicyHisVos.size()>0){
                    if(basePolicyHisVos.get(0).getStatus().equals("2")){
                        //更新数据
                        BasePolicyBo basePBo = BeanUtil.toBean(basePolicyHisVos.get(0), BasePolicyBo.class);
                        BasePolicyHisBo hbo = BeanUtil.toBean(basePolicyHisVos.get(0), BasePolicyHisBo.class);
                        basePBo.setId(basePolicyHisVos.get(0).getPolicyId());
                        basePBo.setStatus("1");
                        iBasePolicyService.updateByBo(basePBo);
                        hbo.setStatus("1");
                        SysUser user = new SysUser();
                        user.setRemark(resp.getData().getOpenId());
                        List<SysUser> users = iSysUserService.selectUserList(user);
                        String username = "";
                        String userId = "";
                        if(!users.isEmpty()){
                            username = users.get(0).getNickName();
                            userId = users.get(0).getUserId().toString();
                        }else{
                            username = resp.getData().getOpenId();
                            userId = resp.getData().getOpenId();
                        }
                        hbo.setApproveUser(userId);
                        hbo.setApproveUserName(username);
                        iBasePolicyHisService.updateByBo(hbo);
                    }
                }
            }else if(resp.getData().getStatus().equals("REJECTED")){
                // 审批拒绝
                BasePolicyHisBo basePolicyHisBo = new BasePolicyHisBo();
                basePolicyHisBo.setInstanceCode(resp.getData().getInstanceCode());


                List<BasePolicyHisVo> basePolicyHisVos = iBasePolicyHisService.queryList(basePolicyHisBo);
                if(list.size()>0){
                    if(list.get(0).getStatus().equals("2")){
                        //更新数据
                        BasePolicyBo baseBo = BeanUtil.toBean(basePolicyHisVos.get(0), BasePolicyBo.class);
                        BasePolicyHisBo hbo = BeanUtil.toBean(basePolicyHisVos.get(0), BasePolicyHisBo.class);
                        baseBo.setId(basePolicyHisVos.get(0).getPolicyId());
                        baseBo.setStatus("3");
                        iBasePolicyService.updateByBo(baseBo);
                        hbo.setStatus("3");
                        SysUser user = new SysUser();
                        user.setRemark(resp.getData().getOpenId());
                        List<SysUser> users = iSysUserService.selectUserList(user);
                        String username = "";
                        String userId = "";
                        if(!users.isEmpty()){
                            username = users.get(0).getNickName();
                            userId = users.get(0).getUserId().toString();
                        }else{
                            username = resp.getData().getOpenId();
                            userId = resp.getData().getOpenId();
                        }
                        hbo.setApproveUser(userId);
                        hbo.setApproveUserName(username);
                        iBasePolicyHisService.updateByBo(hbo);
                    }
                }
            }
            // 处理服务端错误
            if (!resp.success()) {
                System.out.println(String.format("code:%s,msg:%s,reqId:%s"
                    , resp.getCode(), resp.getMsg(), resp.getRequestId()));
                return;
            }

            // 业务数据处理  APPROVED  通过  PENDING  审批中  REJECTED 拒绝
            System.out.println(Jsons.DEFAULT.toJson(resp.getData()));


        }



    }


}
